<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Children;
use App\Models\Classes;
use App\Models\ClassesLogs;
use App\Models\Consume;
use App\Models\PrePaidCard;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{
    protected $month = '';
    protected $now = '';

    public function __construct()
    {
        $this->now = Carbon::now();
        $this->month = [Carbon::create(null, $this->now->month, 1, 0), $this->now];
    }

    public function index(){
        $user = Auth::guard('admin')->user();
        $menulist = $this->getMenu();
        return view('admin.admin', compact('user', 'menulist'));
    }

    public function home(){
        $monthConsumes = $this->monthConsumes();
        $monthCards = $this->monthCards();
        $monthChildren = $this->monthChildren();
        $todayClasses = DB::table('classes as c')
                ->join('teachers as t', 't.teacher_id', '=', 'c.teacher_id')
                ->where('weekday', $this->now->dayOfWeek)
                ->get();
        $courses = DB::table('course_lib as a')
            ->join('course_subject as b', 'a.subject_id', '=', 'b.subject_id')
            ->where('a.week', $this->now->weekOfYear)
            ->select('a.name as class_name', 'b.course_age')
            ->get();
        foreach ($todayClasses as $todayClass){
            foreach ($courses as $course){
                if ($todayClass->course_age == $course->course_age){
                    $todayClass->class_name = $course->class_name;
                }
            }
        }
//        dd($todayClasses);
        return view('admin.index.home', compact('monthConsumes', 'monthCards', 'monthChildren', 'todayClasses'));
    }

    public function getMenu(){
        $menulist= getAllMenu();
        $user = Auth::guard('admin')->user();
        foreach ($menulist as $key => $value){
            if ($user->can($key)){
                foreach ($value['sub_menu'] as $k => $v){
                    if (!$user->can($k)){
                        unset($menulist[$key]['sub_menu'][$k]);
                    }
                }
            }else{
                unset($menulist[$key]);
            }
        }
        return $menulist;
    }

    public function test(){
        
    }

    //当月消耗的课时费
    public function monthConsumes(){
        return Consume::whereBetween('created_at', $this->month)->sum('value');
    }

    //当月新增订单金额
    public function monthCards(){
        $card['value'] = PrePaidCard::whereBetween('created_at', $this->month)->sum('face_value');
        $card['remainder_value'] = PrePaidCard::where('status', 1)->sum('remainder_value');
        return $card;
    }

    //当月新增宝宝
    public function monthChildren(){
        return Children::whereBetween('created_at', $this->month)->count();
    }
}
